from pskpackage.db import *
import requests,time
from lxml import etree
from fake_useragent import UserAgent



#从数据库获取一个ip
def get_ip_one():
    ip=get_db_ip()
    # 记录ip
    if ip:
        insert_detail_ip(ip[1] + ":" + ip[2], '读取ip', 1)
        results = validation_ip(ip[1]+":"+ip[2])  # 验证ip
        if  results:
            return  ip[1]+":"+ip[2]
        else:
            del_ip(ip[0]) # 删除ip
            return  get_ip_one()# 重新获取ip
    else:
        return None


#验证ip
def validation_ip(ip):
    header = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
    }
    url ="http://www.baidu.com"
    try:
        response = requests.get(url, headers=header, proxies={"http": ip}, timeout=3)

        if response.status_code == 200:
            return 1
    except:
        pass
    #验证ip失败
    insert_detail_ip(ip,'验证ip可用性失败', 2)
    return None




